//数组
const data = [
    { "id": 1, "name": "用户中心", "orderNum": 1, "pid": 0 },
    { "id": 2, "name": "订单中心", "orderNum": 2, "pid": 0 },
    { "id": 3, "name": "系统管理", "orderNum": 3, "pid": 0 },
    { "id": 12, "name": "所有订单", "orderNum": 1, "pid": 2 },
    { "id": 14, "name": "待发货", "orderNum": 1.2, "pid": 2 },
    { "id": 15, "name": "订单导出", "orderNum": 2, "pid": 2 },
    { "id": 18, "name": "菜单设置", "orderNum": 1, "pid": 3 },
    { "id": 19, "name": "权限管理", "orderNum": 2, "pid": 3 },
    { "id": 21, "name": "系统权限", "orderNum": 1, "pid": 19 },
    { "id": 22, "name": "角色设置", "orderNum": 2, "pid": 19 },
    ];
    
//树
const tree = [
    { "id": 1, "name": "用户中心", "pid": 0 },
    {
        "id": 2, "name": "订单中心", "pid": 0,
        "children": [
            { "id": 12, "name": "所有订单", "pid": 2 },
            { "id": 14, "name": "待发货", "pid": 2 },
            { "id": 15, "name": "订单导出","pid": 2 }
        ]
    },
    {
        "id": 3, "name": "系统管理", "pid": 0,
        "children": [
            { "id": 18, "name": "菜单设置", "pid": 3 },
            {
                "id": 19, "name": "权限管理", "pid": 3,
                "children": [
                    { "id": 21, "name": "系统权限",  "pid": 19 },
                    { "id": 22, "name": "角色设置",  "pid": 19 }
                ]
            }
        ]
    }
]

//#region 数组转树
//方法一
/**
 * @description:
 * @param {*} items
 * @param {*} pid:根节点,默认0
 * @return {*}
 */
function buildTree(items, pid = 0) {
    //查找pid子节点
    let pitems = items.filter(s => s.pid === pid)
    if (!pitems || pitems.length <= 0)
      return null
    //递归
    pitems.forEach(item => {
      const res = buildTree(items, item.id)
      if (res && res.length > 0)
        item.children = res
    })
    return pitems
  }
  
  //方法二
  /**
   * 集合数据转换为树形结构。option.parent支持函数，示例：(n) => n.meta.parentName
   * @param {Array} list 集合数据
   * @param {Object} option 对象键配置，默认值{ key: 'id', parent: 'pid', children: 'children' }
   * @returns 树形结构数据tree
   */
  function list2Tree(list, option = { key: 'id', parent: 'pid', children: 'children' }) {
    let tree = []
    // 获取父编码统一为函数
    let pvalue = typeof (option.parent) === 'function' ? option.parent : (n) => n[option.parent]
    // map存放所有对象
    let map = {}
    list.forEach(item => {
      map[item[option.key]] = item
    })
    //遍历设置根节点、父级节点
    list.forEach(item => {
      if (!pvalue(item))
        tree.push(item)
      else {
        map[pvalue(item)][option.children] ??= []
        map[pvalue(item)][option.children].push(item)
      }
    })
    return tree
  }
//#endregion

//#region 树转列表
/**
 * 树形转平铺list（广度优先，先横向再纵向）
 * @param {*} tree 一颗大树
 * @param {*} option 对象键配置，默认值{ children: 'children' }
 * @returns 平铺的列表
 */
function tree2List(tree, option = { children: 'children' }) {
    const list = []
    const queue = [...tree]
    while (queue.length) {
      const item = queue.shift()
      if (item[option.children]?.length > 0)
        queue.push(...item[option.children])
      list.push(item)
    }
    return list
  }
//#endregion








/**
 * 数组转tree结构
 * @param {Array} data
 * @returns tree：数结构数据，list：原始数据，cloneList：原始数据副本
 */
export function arrayToTree(data, showCode = false, isDisableGroup = false) {
  let cloneList = _.cloneDeep(data);
  let result = [];
  let map = {};
  data.forEach((item) => {
    map[item.id] = item;
    item.value = item.id;
    item.label = item.name;
    item.children = [];
  });
  data.forEach((item) => {
    let parent = map[item.parentId];
    if (parent) {
      if (showCode) {
        item.label = (item.code == null || item.code == "" ? "" : "[" + item.code + "] ") + item.name;
      }
      (parent.children || (parent.children = [])).push(item);
    } else {
      if (showCode) {
        item.label = (item.code == null || item.code == "" ? "" : "[" + item.code + "] ") + item.name;
      }
      result.push(item);
    }
  });
  return { tree: result, list: data, cloneList: cloneList };
}

/**
 * 数组转tree结构
 * @param {Array} data
 * @returns tree：数结构数据，list：原始数据，cloneList：原始数据副本
 */
export function arrayToTreeForParam(data, showCode = false, isDisableGroup = false) {
  let cloneList = _.cloneDeep(data);
  let result = [];
  let map = {};
  data.forEach((item) => {
    map[item.id] = item;
    item.value = item.id;
    item.label = item.name;
    item.children = [];
  });
  data.forEach((item) => {
    let parent = map[item.parentId];
    if (isDisableGroup) {
      item.disabled = !item.type || item.type == enumUtil.enumDataRevers.ParamTypeEnum.参数组;
    }
    if (parent) {
      if (showCode) {
        item.label = "[" + item.code + "] " + item.name;
      }
      (parent.children || (parent.children = [])).push(item);
    } else {
      if (showCode) {
        item.label = "[" + item.code + "] " + item.name;
      }
      result.push(item);
    }
  });
  return { tree: result, list: data, cloneList: cloneList };
}

/**
 * 获取tree的sort数组
 * @param {*} tree
 * @param {*} arr 排序后数组
 * @returns
 */
export function getTreeSortArr(tree, arr, index = 0) {
  tree.forEach((node) => {
    if (!node.isRoot) {
      arr.push({ id: node.id, sort: index });
      index++;
    }
    if (node.children && node.children.length > 0) {
      index = getTreeSortArr(node.children, arr, index);
    }
  });
  return index;
}

/**
 * tree转数组
 * @param {*} tree
 * @param {*} arr
 * @returns
 */
export function treeToArr(tree, arr) {
  tree.forEach((node) => {
    arr.push({ ...node });
    if (node.children && node.children.length > 0) {
      treeToArr(node.children, arr);
    }
  });
}
